<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 警告条 -->
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
      <!-- 步骤条 -->
      <el-steps :space="200" :active="activeIndex-0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- tab栏 -->
      <!-- 添加form表单 要包裹整个tabs组件 而不是只包裹pane -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-position="top">
        <el-tabs
          v-model="activeIndex"
          tab-position="left"
          :before-leave="beforeTabLeave"
          @tab-click="tabClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item v-model="addForm.goods_cat" label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                expand-trigger="hover"
                :options="catelist"
                :props="cateProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>

          <!-- ===============-商品参数-==================== -->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.attr_id">
              <!-- 复选框组 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="cb" v-for="(cb, i) in item.attr_vals" :key="i" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              :action="uploadAddress"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="uploadHeaders"
              :on-success="successCallBack"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器组件 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <!-- 添加商品的按钮 -->
            <el-button type="primary" class="btnAdd" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览 -->
    <el-dialog title="图片预览" :visible.sync="previewVisible" width="50%">
      <img :src="previewPath" alt class="previewImg" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      uploadAddress: "http://127.0.0.1:8888/api/private/v1/upload",
      activeIndex: "0",
      addForm: {
        goods_name: "",
        goods_price: "",
        goods_weight: "",
        goods_number: "",
        goods_cat: [], // 添加商品时 这个分类的数据 还没有同步
        pics: [],
        goods_introduce:""
      },
      addFormRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" }
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" }
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" }
        ],
        goods_cat: ""
      },
      catelist: [],
      cateProps: {
        label: "cat_name",
        value: "cat_id",
        children: "children"
      },
      manyTableData: [],
      onlyTableData: [],
      uploadHeaders: {
        Authorization: window.sessionStorage.getItem("token")
      },
      previewPath: "",
      previewVisible: false
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status == 200) {
        this.catelist = res.data;
      } else {
        this.$message.error("分类数据获取失败");
      }
    },
    handleChange() {
      if (this.addForm.goods_cat.length < 3) {
        this.addForm.goods_cat = [];
      }
    },
    beforeTabLeave(newactive, oldactive) {
      if (oldactive == "0" && this.addForm.goods_cat.length != 3) {
        this.$message.error("请选择商品分类");
        return false;
      }
    },
    async tabClick() {
      // 如果activeIndex为1 表明此时tab页为商品参数页
      if (this.activeIndex == "1") {
        // 获取已经选择的商品分类下的动态参数
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: {
              sel: "many"
            }
          }
        );
        if (res.meta.status != 200) {
          return this.$message.error("动态参数获取失败");
        }
        res.data.forEach(item => {
          // 把item中的attr_vals从字符串转化为[]
          if (item.attr_vals == "") {
            item.attr_vals = [];
          } else {
            item.attr_vals = item.attr_vals.split(" ");
          }
        });
        console.log(res.data);
        this.manyTableData = res.data;
      } else if (this.activeIndex == "2") {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: {
              sel: "only"
            }
          }
        );
        if (res.meta.status != 200) {
          return this.$message.error("动态参数获取失败");
        }
        this.onlyTableData = res.data;
      }
    },
    handlePreview(file) {
      this.previewPath = file.response.data.url;
      this.previewVisible = true;
    },
    handleRemove(file) {
      // 获取当前移除的图片路径
      const picPath = file.response.data.tmp_path;
      // 查找addForm pics属性中对应值的索引
      const pIndex = this.addForm.pics.findIndex(item => item.pic === picPath);
      // 根据索引去pics中移除该地址
      this.addForm.pics.splice(pIndex, 1);
      console.log(this.addForm);
    },
    successCallBack(response) {
      if (response.meta.status == 200) {
        this.$message.success("上传成功");
        this.addForm.pics.push({ pic: response.data.tmp_path });
      } else {
        return this.$message.error("上传失败");
      }
    },
    async add() {
      // 对addForm中的goods_cat做一个处理 加工为,分割的字符串
      // 因为goods_cat与级联选择器双向绑定在了一起所以不能直接修改addForm 需要进行一次深拷贝
      // 可以选择利用lodash工具 也可以直接如下实现深拷贝
      var form = JSON.parse(JSON.stringify(this.addForm));
      form.goods_cat = form.goods_cat.join(",");
      form.attrs = [];
      // 处理动态参数
      this.manyTableData.forEach(item => {
        const newInfo = {
          attr_id: item.attr_id,
          attr_value: item.attr_vals.join(" ")
        };
        form.attrs.push(newInfo);
      });
      // 处理静态属性
      this.onlyTableData.forEach(item => {
        const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals };
        form.attrs.push(newInfo);
      });
      const { data:res } = await this.$http.post('goods',form)
      if(res.meta.status != 201){
        return this.$message.error('添加失败')
      }
      this.$message.success('成功')
      this.$router.push('/goods') // 注意要加 / 表示服务器的根域名 如果不加/ 会拼在当前的路由后面
    }
  },
  computed: {
    cateId() {
      return this.addForm.goods_cat[2];
    }
  }
};
</script>

<style lang="less" scoped>
.el-checkbox {
  margin: 0 10px 0 0 !important;
}

.previewImg {
  width: 100%;
}

.btnAdd {
  margin-top: 15px;
}

.ql-editor {
  min-height: 300px;
}
</style>